package cn.pconline.autoclub.web;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.util.ClubModule;
import cn.pconline.autoclub.entity.ClubModuleRelation;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.ClubModuleService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.util.WebUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author ppc
 */
@Controller
public class ClubModuleController {

    @Autowired
    private ClubModuleService clubModuleService;
    @Autowired
    private ClubService clubService;
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private MemberService memberService;
    private static final int STATUS_OK = 0;
    private static final int STATUS_ERROR = -1;

    private void printMsg(HttpServletResponse resp, String msg, String callback) {
        PrintWriter out = null;
        try {
            out = resp.getWriter();
            if (StringUtils.isBlank(callback)) {
                out.println(msg);
            } else {
                out.println(callback + "(" + msg + ")");
            }
            out.flush();
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(ClubModuleController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    private void printSuccessMsg(HttpServletResponse resp, String msg, String callback) {
        JSONObject obj = new JSONObject();
        obj.put("code", STATUS_OK);
        obj.put("message", msg);
        printMsg(resp, obj.toJSONString(), callback);
    }

    private void printErrorMsg(HttpServletResponse resp, String msg, String callback) {
        JSONObject obj = new JSONObject();
        obj.put("code", STATUS_ERROR);
        obj.put("message", msg);
        printMsg(resp, obj.toJSONString(), callback);
    }

    /**
     * 修改模块接口
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/module/addClubModule.do")
    public void addClubModule(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        String formData = WebUtils.param(req, "data", "");
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            printErrorMsg(resp, "车友会不存在", null);
            return;
        }
        User user = userAuth.getUser(req, resp);
        if (!isLogin(user)) {
            printErrorMsg(resp, "请先登录", null);
            return;
        }
        //是否会长
        if (!memberService.isClubNormalAdmin(user.getUid(), clubId)) {
            printErrorMsg(resp, "只有管理员才能操作", null);
            return;
        }
        JSONArray array = JSONArray.parseArray(formData);
        if (array != null && !array.isEmpty()) {
            List<ClubModuleRelation> relations = new ArrayList<ClubModuleRelation>();
            for (int i = 0; i < array.size(); i++) {
                JSONObject obj = array.getJSONObject(i);
                ClubModule clubModule = clubModuleService.getClubModule(obj.getLong("id"));
                if (clubModule == null) {
                    printErrorMsg(resp, "找不到该模块", null);
                    return;
                }
                ClubModuleRelation clubModuleRelation = new ClubModuleRelation();
                clubModuleRelation.setModuleId(clubModule.getModuleId());
                clubModuleRelation.setClubId(clubId);
                int status = obj.getInteger("status");
                clubModuleRelation.setStatus(status == ClubModuleRelation.STATUS_NORMAL ? ClubModuleRelation.STATUS_NORMAL : ClubModuleRelation.STATUS_HIDDEN);
                clubModuleRelation.setSeq(obj.getInteger("seq"));
                relations.add(clubModuleRelation);
            }
            int count = clubModuleService.addOrUpdateClubModules(relations);
            if (count > 0) {
                printSuccessMsg(resp, "保存成功", null);
            } else {
                printErrorMsg(resp, "保存失败", null);
            }
        }

    }

    /**
     * 修改模块(页面)
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/module/editModule.do", method = RequestMethod.GET)
    public String editModule(HttpServletRequest req, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            sendError(resp, 404);
            return null;
        }
        User user = userAuth.getUser(req, resp);
        if (!isLogin(user)) {
            return "redirect:" + systemConfig.getUcRoot() + "/passport/login.jsp?return=" + systemConfig.getRoot() + "/module/editModule.do?clubId=" + clubId;
        }
        //是否会长
        if (!memberService.isClubNormalAdmin(user.getUid(), clubId)) {
            sendError(resp, 403);
            return null;
        }
        List<ClubModuleRelation> modules = clubModuleService.listAllClubModuleRelationsByClub(clubId);
        req.setAttribute("modules", modules);
        req.setAttribute("user", user);
        ClubController.setClubStyle(req, clubId);
        return "template/club/editModule";
    }

    /**
     * 判断是否登录
     *
     * @param user
     * @return
     */
    private boolean isLogin(User user) {
        if (user == null || user.getUid() == 0) {
            return false;
        }
        return true;
    }

    private void sendError(HttpServletResponse resp, int code) {
        try {
            resp.sendError(code);
        } catch (IOException ex) {
            Logger.getLogger(ClubModuleController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
